<?php
/**
 * Created by PhpStorm.
 * User: sunzexin
 * Date: 2018/1/5
 * Time: 14:20
 */

namespace App\Http\Logics\MiniProgram;


use App\Auth;
use App\Menu;
use App\MenuMappingAuth;
use App\Partner;
use App\Role;
use App\RoleMappingMenu;
use App\UserMappingRole;
use App\Users;
use Illuminate\Support\Facades\DB;
use App\Http\Logics\BaseLogic;
class MenuLogic extends BaseLogic
{
    /**
     * 获取菜单列表
     * @param $data 筛选条件
     * @return mixed 返回结果
     */
    public static function getYiiccaMenuList($data)
    {
        try{
            $query = new Menu();
            // 条件筛选
            $query = $query->where(function ($query) use ($data){
                $query->where('parent_id', $data['parent_id']);
                // 因为type可能是0,所以不能用empty函数来判断
                if ($data['type'] !== ''){
                    $query->where('type', $data['type']);
                }else{
                    $query->where('type', Menu::ADMIN_MENU);
                }
                if (!empty($data['name'])){
                    $query->where('name', 'like', '%'.$data['name'].'%');
                }
            })->orderBy('id', 'desc');
            // 判断是否分页
            $menu = $data['limit'] ? $query->paginate($data['limit']) : $query->get();
            if (empty($menu)){
                return self::response(self::CONTENT_IS_EMPTY);
            }
            return self::response(self::SUCCESS, $menu);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 获取菜单列表
     * @param $data 筛选条件
     * @return mixed 返回结果
     */
    public static function getMiniProgramMenuList($data)
    {
//        try{
            $query = new Menu();
            // 条件筛选
            $query = $query->where(function ($query) use ($data){
                $query->where('parent_id', $data['parent_id']);
                // 因为type可能是0,所以不能用empty函数来判断
                if ($data['type'] !== ''){
                    $query->where('type', $data['type']);
                }else{
                    $query->where('type', Menu::ADMIN_MENU)->orWhere('type', Menu::COMMON_MENU);
                }
                if (!empty($data['name'])){
                    $query->where('name', 'like', '%'.$data['name'].'%');
                }
                if ($data['has_qrcode'] != ''){
                    $query->where('has_qrcode', $data['has_qrcode']);
                }
            })->orderBy('id', 'desc');
            // 判断是否分页
            $menu = $data['limit'] ? $query->paginate($data['limit']) : $query->get();
            if (empty($menu)){
                return self::response(self::CONTENT_IS_EMPTY);
            }
            return self::response(self::SUCCESS, $menu);
//        }catch (\Exception $e){
//            return self::response(self::SYSTEM_ERROR);
//        }
    }

    public static function getAllMenuList()
    {
        try{
            $first_menu = Menu::where('parent_id', 0)->get();
            foreach ($first_menu as $item){
                $second_menu = Menu::where('parent_id', $item->id)->get();
                $item->second_menu = $second_menu;
            }
            if (empty($first_menu)){
                return self::response(self::CONTENT_IS_EMPTY);
            }
            return self::response(self::SUCCESS, $first_menu);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 创建菜单
     * @param $data 菜单信息
     * @return mixed 返回结果
     */
    public static function createMenu($data)
    {
        try{
            $menu = new Menu();
            $menu->parent_id = $data['parent_id'];
            $menu->name = $data['name'];
            $menu->path = $data['path'];
            $menu->type = $data['type'];
            $menu->icon = $data['icon'];
            if (!$menu->save()){
                return self::response(self::OBJECT_SAVE_FAIL);
            }
            return self::response(self::SUCCESS, $menu);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 删除菜单
     * @param $data 筛选条件
     * @return mixed 返回结果
     * @throws \Exception
     */
    public static function deleteMenu($data)
    {
        try{
            $menu = Menu::find($data['id']);
            if (!$menu->delete()){
                return self::response(self::OBJECT_DELETE_FAILD);
            }
            return self::response(self::SUCCESS);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 更新菜单
     * @param $data 菜单信息
     * @return mixed 返回结果
     */
    public static function updateMenu($data)
    {
        try{
            $menu = Menu::find($data['id']);
            if (empty($menu)){
                return self::response(self::CONTENT_IS_EMPTY);
            }
            $menu->name = $data['name'];
            $menu->path = $data['path'];
            $menu->type = $data['type'];
            $menu->icon = $data['icon'];
            if (!$menu->save()){
                return self::response(self::OBJECT_SAVE_FAIL);
            }
            return self::response(self::SUCCESS, $menu);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    public static function setMenuIcon($data)
    {
        try{
            $url = uploadImage(storage_path().'/app/'.$data['icon_file'], 'icon');
            return self::response(self::SUCCESS, $url);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 获取菜单列表
     * @param $data 筛选条件
     * @return mixed 返回结果
     */
    public static function getMenuList($data)
    {
        try{
            $query = new Menu();
            // 条件筛选
            $query = $query->where(function ($query) use ($data){
                $query->where('parent_id', $data['parent_id']);
                // 因为type可能是0,所以不能用empty函数来判断
                if ($data['type'] !== ''){
                    $query->where('type', $data['type']);
                }
                if (!empty($data['name'])){
                    $query->where('name', 'like', '%'.$data['name'].'%');
                }
            })->orderBy('id', 'desc');
            // 判断是否分页
            $menu = $data['limit'] ? $query->paginate($data['limit']) : $query->get();
            $menu->map(function ($menu) {
                return $menu->append('has_qrcode_bool');
            });
            $menu->map(function ($menu) {
                return $menu->append('type_text');
            });
            $menu->map(function ($menu) {
                return $menu->append('root_menu_bool');
            });
            if (empty($menu)){
                return self::response(self::CONTENT_IS_EMPTY);
            }
            return self::response(self::SUCCESS, $menu);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    public static function getMenuByMenuId($data)
    {
        try{
            $menu_id_arr = explode(',', $data['menu_id_str']);
            $menu = Menu::whereIn('id', $menu_id_arr)->get();
            if (empty($menu)){
                return self::response(self::CONTENT_IS_EMPTY);
            }
            return self::response(self::SUCCESS, $menu);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 通过用户ID获取用户的管理菜单
     * @param $data 筛选条件
     * @return mixed 返回结果
     */
    public static function getMenuListByUserId($data)
    {
        $user_mapping_role = UserMappingRole::where('user_id', $data['user_id'])->first();
        if (empty($user_mapping_role)){
            return self::response(self::CONTENT_IS_EMPTY);
        }

        $role = Role::with(['menu' => function ($query){
            $query->select('menu.id', 'menu.name', 'menu.type', 'menu.has_qrcode');
        }])->select('id', 'name')->find($user_mapping_role->role_id);
        if (empty($role)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        return self::response(self::SUCCESS, $role);
    }

    public static function updateMenuByUserId($data)
    {
//        try{
            $user_mapping_role = UserMappingRole::where('user_id', $data['user_id'])->first();
            if (empty($user_mapping_role)){
                return self::response(self::CONTENT_IS_EMPTY);
            }

            $role_mapping_menu = RoleMappingMenu::where('role_id', $user_mapping_role->role_id)->get();
            if (empty($role_mapping_menu)){
                return self::response(self::CONTENT_IS_EMPTY);
            }

            // 创建事务,更新咖啡馆小程序管理员用户的菜单
            DB::transaction(function () use ($data, $role_mapping_menu, $user_mapping_role) {
                foreach ($role_mapping_menu as $item) {
                    if (!$item->delete()) {
                        return self::response(self::OBJECT_DELETE_FAILD);
                    }
                }

                $menu_id_arr = explode(',', $data['menu_id_str']);
                foreach ($menu_id_arr as $menu_id) {
                    $role_mapping_menu = new RoleMappingMenu();
                    $role_mapping_menu->menu_id = $menu_id;
                    $role_mapping_menu->role_id = $user_mapping_role->role_id;
                    if (!$role_mapping_menu->save()) {
                        return self::response(self::OBJECT_SAVE_FAIL);
                    }
                }
            });

            return self::response(self::SUCCESS);
//        }catch (\Exception $e){
//            return self::response(self::SYSTEM_ERROR);
//        }
    }


    /**
     * 咖啡馆小程序用户获取菜单
     * @param $data 筛选条件
     * @return mixed 返回结果
     */
    public static function getUserMiniProgramMenu($data)
    {
//        try{
            $query = new Menu();
            $response = self::getUserIdByLoginSession($data['loginSession']);
            if ($response->code){
                return self::response(self::CONTENT_IS_EMPTY);
            }
            $user_id = $response->data;

            $user_mapping_role = UserMappingRole::where('user_id', $user_id)->first();

            // 声明一个菜单ID数组，用于存放根据用户角色取出来的菜单ID
            $menu_list_arr = [];

            // 判断角色是否为空，为空则为普通用户，否则为管理员用户
            if (empty($user_mapping_role)){
                $user = Users::find($user_id);
                $partner = Partner::find($user->partner_id);
                $menu_list = RoleMappingMenu::where('role_id', $partner->role_id)->get();
                foreach ($menu_list as $menu){
                    array_push($menu_list_arr, $menu->menu_id);
                }
                $query = $query->where('type', Menu::COMMON_MENU);
            }else{
                // 找到该角色，判断该角色的类型
                $role = Role::find($user_mapping_role->role_id);

                if ($role->type == Role::CAFE_MINI_PROGRAM){
                    $menu_list = RoleMappingMenu::where('role_id', $user_mapping_role->role_id)->get();
                    foreach ($menu_list as $menu){
                        array_push($menu_list_arr, $menu->menu_id);
                    }
                }elseif ($role->type == Role::CAFE_MINI_PROGRAM_MANAGER){
                    // 找到该用户的合作者ID
                    $user = Users::find($user_id);
                    if (empty($user)){
                        return self::response(self::CONTENT_IS_EMPTY);
                    }
                    $partner_id = $user->partner_id;

                    // 找到该合作者
                    $partner = Partner::find($partner_id);
                    if (empty($partner)){
                        return self::response(self::CONTENT_IS_EMPTY);
                    }

                    // 获取到该合作者的角色
                    $role_id = $partner->role_id;

                    // 获取到该小程序角色的普通用户菜单，并添加到菜单数组中
                    $menu_list = Role::with(['menu' => function ($query){
                        $query->where('type', Menu::COMMON_MENU);
                    }])->find($role_id);

                    foreach ($menu_list->menu as $menu){
                        array_push($menu_list_arr, $menu->id);
                    }

                    // 获取到该小程序管理员自己的管理菜单，并添加到菜单数组中
                    $menu_list = RoleMappingMenu::where('role_id', $user_mapping_role->role_id)->get();
                    foreach ($menu_list as $menu){
                        array_push($menu_list_arr, $menu->menu_id);
                    }
                }
            }
            // 将菜单取出来并分局菜单的类型分组返回
            $menu = $query->whereIn('id', $menu_list_arr)->get()->groupBy('type');
            if (empty($menu)){
                return self::response(self::CONTENT_IS_EMPTY);
            }

            // 给结果加一层包装，方便前端判断用户是什么身份
            $return_data['menu'] = $menu;
            $return_data['is_common'] = empty($user_mapping_role) ?  Menu::COMMON_MENU : Menu::ADMIN_MENU;

            return self::response(self::SUCCESS, $return_data);
//        }catch (\Exception $e){
//            return self::response(self::SYSTEM_ERROR);
//        }
    }

    public static function getMenuListHasQrcode($data)
    {
        $query = new Menu();
        $query = $query->where(function ($query) use ($data){
            if ($data['has_qrcode'] != ''){
                $query->where('has_qrcode', $data['has_qrcode']);
            }
        });
        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        $user_id = $response->data;

        $user_mapping_role = UserMappingRole::where('user_id', $user_id)->first();

        // 声明一个菜单ID数组，用于存放根据用户角色取出来的菜单ID
        $menu_list_arr = [];

        // 判断角色是否为空，为空则为普通用户，否则为管理员用户
        if (empty($user_mapping_role)){
            $user = Users::find($user_id);
            $partner = Partner::find($user->partner_id);
            $menu_list = RoleMappingMenu::where('role_id', $partner->role_id)->get();
            foreach ($menu_list as $menu){
                array_push($menu_list_arr, $menu->menu_id);
            }
            $query = $query->where('type', Menu::COMMON_MENU);
        }else{
            // 找到该角色，判断该角色的类型
            $role = Role::find($user_mapping_role->role_id);

            if ($role->type == Role::CAFE_MINI_PROGRAM){
                $menu_list = RoleMappingMenu::where('role_id', $user_mapping_role->role_id)->get();
                foreach ($menu_list as $menu){
                    array_push($menu_list_arr, $menu->menu_id);
                }
            }elseif ($role->type == Role::CAFE_MINI_PROGRAM_MANAGER){
                // 找到该用户的合作者ID
                $user = Users::find($user_id);
                if (empty($user)){
                    return self::response(self::CONTENT_IS_EMPTY);
                }
                $partner_id = $user->partner_id;

                // 找到该合作者
                $partner = Partner::find($partner_id);
                if (empty($partner)){
                    return self::response(self::CONTENT_IS_EMPTY);
                }

                // 获取到该合作者的角色
                $role_id = $partner->role_id;

                // 获取到该小程序角色的普通用户菜单，并添加到菜单数组中
                $menu_list = Role::with(['menu' => function ($query){
                    $query->where('type', Menu::COMMON_MENU);
                }])->find($role_id);

                foreach ($menu_list->menu as $menu){
                    array_push($menu_list_arr, $menu->id);
                }

                // 获取到该小程序管理员自己的管理菜单，并添加到菜单数组中
                $menu_list = RoleMappingMenu::where('role_id', $user_mapping_role->role_id)->get();
                foreach ($menu_list as $menu){
                    array_push($menu_list_arr, $menu->menu_id);
                }
            }
        }
        // 将菜单取出来并分局菜单的类型分组返回
        $menu = $query->whereIn('id', $menu_list_arr)->get();
        if (empty($menu)){
            return self::response(self::CONTENT_IS_EMPTY);
        }

        return self::response(self::SUCCESS, $menu);
    }

    public static function setMenuHasQrcode($data)
    {
        $menu = Menu::find($data['menu_id']);
        if (empty($menu)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        $menu->has_qrcode = !$menu->has_qrcode;
        if (!$menu->save()){
            return self::response(self::OBJECT_SAVE_FAIL);
        }
        return self::response(self::SUCCESS);
    }

    public static function getMenuAuthList($data)
    {
        $auth_id_arr = MenuMappingAuth::where('menu_id', $data['menu_id'])->select('auth_id')->get();
        if (empty($auth_id_arr)){
            return self::response(self::CONTENT_IS_EMPTY);
        }

        $query = Auth::whereIn('id', $auth_id_arr);

        $auth = $data['limit'] ? $query->paginate($data['limit']) : $query->get();
        if (empty($auth)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        return self::response(self::SUCCESS, $auth);
    }

    public static function setMenuAuth($data)
    {
        $menu_mapping_auth = new MenuMappingAuth();
        $menu_mapping_auth->menu_id = $data['menu_id'];
        $menu_mapping_auth->auth_id = $data['auth_id'];
        if (!$menu_mapping_auth->save()){
            return self::response(self::OBJECT_SAVE_FAIL);
        }
        return self::response(self::SUCCESS);
    }

    public static function deleteMenuAuth($data)
    {
        $menu_mapping_auth = MenuMappingAuth::find($data['id']);
        if (empty($menu_mapping_auth)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        if (!$menu_mapping_auth->delete()){
            return self::response(self::OBJECT_DELETE_FAILD);
        }
        return self::response(self::SUCCESS);
    }

    /**
     * 获取管理员所有可以访问的路由列表，用于中间键鉴权
     * @param $data
     * @return mixed
     */
    public static function getAdminRouteList($data)
    {
        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code) {
            return self::response(self::CONTENT_IS_EMPTY);
        }
        $user_id = $response->data;
        // 通过user_id获取到该用户的角色列表
        $user_mapping_role = UserMappingRole::where('user_id', $user_id)->get();

        // 判断角色是否为空，为空则为一间咖啡馆普通用户，否则为一间咖啡馆角色用户
        if ($user_mapping_role->isEmpty()) {
            $auth_route_arr = [];
        } else {
            $role_arr = [];
            foreach ($user_mapping_role as $item) {
                array_push($role_arr, $item->role_id);
            }

            $menu_id_arr = RoleMappingMenu::whereIn('role_id', $role_arr)->select('menu_id')->get();
            if (empty($menu_id_arr)){
                return self::response(self::CONTENT_IS_EMPTY);
            }

            $menu_id_arr = Menu::whereIn('id', $menu_id_arr)->select('id')->get();
            if (empty($menu_id_arr)){
                return self::response(self::CONTENT_IS_EMPTY);
            }

            $auth_id_arr = MenuMappingAuth::whereIn('menu_id', $menu_id_arr)->select('auth_id')->get();
            if (empty($menu_id_arr)){
                return self::response(self::CONTENT_IS_EMPTY);
            }

            $auth_route_arr = Auth::whereIn('id', $auth_id_arr)->select('route')->get();

            if (empty($auth_route_arr)){
                return self::response(self::CONTENT_IS_EMPTY);
            }
        }


        return self::response(self::SUCCESS, $auth_route_arr);
    }

    public static function setMenuRootMenu($data)
    {
        $menu = Menu::find($data['menu_id']);
        if (empty($menu)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        $menu->root_menu = !$menu->root_menu;
        if (!$menu->save()){
            return self::response(self::OBJECT_SAVE_FAIL);
        }
        return self::response(self::SUCCESS);
    }
}